﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MyLib.Web {
	/// <summary>
	/// Enable async page.
	/// But it has no use actually, see HttpApplication.ExecuteInternal
	/// </summary>
	public sealed class PageAsyncHandlerFactory : System.Web.UI.PageHandlerFactory {
		/// <summary>
		/// 
		/// </summary>
		private class HandlerWrapper : IHttpAsyncHandler {
			private IHttpHandler m_handler;

			/// <summary>
			/// 
			/// </summary>
			/// <param name="context"></param>
			/// <param name="cb"></param>
			/// <param name="extraData"></param>
			/// <returns></returns>
			public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {
				Action func = () => {
					HttpContext.Current = context;

					ProcessRequest(context);
				};

				return func.BeginInvoke(cb, extraData);
			}

			/// <summary>
			/// 
			/// </summary>
			/// <param name="result"></param>
			public void EndProcessRequest(IAsyncResult result) {
			}

			/// <summary>
			/// 
			/// </summary>
			public bool IsReusable {
				get { return false; }
			}

			/// <summary>
			/// 
			/// </summary>
			/// <param name="context"></param>
			public void ProcessRequest(HttpContext context) {
				m_handler.ProcessRequest(context);
			}

			/// <summary>
			/// 
			/// </summary>
			/// <param name="handler"></param>
			public HandlerWrapper(IHttpHandler handler) {
				System.Diagnostics.Debug.Assert(handler != null);

				m_handler = handler;
			}
		} // end of HandlerWrapper.

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="requestType"></param>
		/// <param name="virtualPath"></param>
		/// <param name="path"></param>
		/// <returns></returns>
		public override System.Web.IHttpHandler GetHandler(System.Web.HttpContext context, string requestType, string virtualPath, string path) {
			return new HandlerWrapper(base.GetHandler(context, requestType, virtualPath, path));
		}
	} // end of PageAsyncHandlerFactory.
}
